#!/usr/bin/python
# -*- coding:utf-8 -*-

"""Update Histroy:
2012-10-18 :Start

"""
__version__ = "1.0.1"
__author__ = "zhaochunhai"

import maya.cmds as mc
import maya.mel as mel
import maya.OpenMaya as om
import re,os

import tools_Persional.LZ_Tools.LZ_Tools.OF3D_PublicClass.mayaPrint as mayaPrint

class QualityAssurance( mayaPrint.MayaPrint ):
    def __init__(self):
        mayaPrint.MayaPrint.__init__(self)
        
    #down form here is common method
    def getMasterGrp(self):
        "get outer line root master group"
        topGroup = mc.ls("|*",type="transform")
        cyleList = topGroup[:]
        for x in cyleList:
            shape = mc.listRelatives(x,shapes=True)
            if shape!=None:
                topGroup.remove(x)
        if len(topGroup)!=1:
            warningStr = "Not 1 master group in this scene //"
            self.mayaError(warningStr,True)
            raise TypeError(warningStr)
            #self.mayaWarning("Maybe there is more than 1 master group //")
            #return
        masterGrp = topGroup[0]
        return masterGrp
        
    def qa_ckFileName(self,depPartMent="MDL",subd="HI",fileType="ma",printInWin=0):
        """depPartMent = "Rig"
        subd = "HI"
        fileType="ma"
        """
        #fPath = "D:/dragon/_assets/char/human/astrid/astrid_heather/models/MDL/astrid_heather_MDL_HI.ma"
        masterGrp = self.getMasterGrp()
        thisFilePath = mc.file(q=1,loc=True)
        if thisFilePath=="unknown":
            self.mayaWarning( "unknown the location of the given file name." )
            return "unknown"
        pathName = os.path.split( thisFilePath )
        rootExt = os.path.splitext( pathName[1] )
        
        STANDARDFILENAME = "%s_%s_%s.%s"%(masterGrp,depPartMent,subd,fileType)
        
        if pathName[1]==STANDARDFILENAME:
            #print self.qa_manyVersionFile(thisFilePath)
            self.mayaPrint("Standard File Name <%s>"%(STANDARDFILENAME) ,printInWin)
            return True
        else:
            self.mayaError( STANDARDFILENAME ,printInWin)
            return False
        
    def qa_manyVersionFile(self,path,fill=2):
        "input a master file file full path,version length"
        fileName = os.path.basename(path)
        file_ma = os.path.splitext(fileName) 
        dirName = os.path.dirname(path) 
        verFolder = "%s/ver"%(dirName)
        if not os.path.exists(verFolder):
            return 0,[]
        allInVer = os.listdir( verFolder )
        allVerFiles = []
        verValue = 0
        for f in allInVer:
            vfile = "%s/%s"%(verFolder,f)
            serIt = re.search("^%s_[v|V][\d]{%d}%s"%(file_ma[0],fill,file_ma[1]),f)
            if os.path.isfile(vfile) and serIt!=None:
                hasNumber = re.search("[\d]{%s}"%(fill),vfile)
                if hasNumber!=None:
                    thisValue = int( hasNumber.group() )
                    #get max version number
                    if thisValue>verValue:
                        verValue = thisValue
                #put verfile name in a list
                allVerFiles.append( vfile )
        #make it writeable
        if os.path.exists(path) and os.stat(path).st_mode==33060:
            os.chmod(path,stat.S_IWRITE )
        #the max version,version file list
        return verValue,allVerFiles
        
    #down form here is check method
    def qa_hasRepeatName(self,printInWin=0):
        "check transform and mesh repeatName"
        allCheck = mc.ls(type=["mesh","transform"])
        res = []
        for x in allCheck:
            if "|" in x:
                res.append( x )
        if res == []:
            self.mayaPrint("No Repeat Name Object",printInWin)
        else:
            for obj in res:
                self.mayaWarning("Repeat Name Object <%s>"%(obj),printInWin,command="from maya import cmds\ncmds.select('%s')"%(obj) )
        return res
        
    def qa_ckInstanceCopy(self,printInWin=0):
        dagItr = om.MItDag()
        dagPath = om.MDagPath()
        dagNode = om.MFnDagNode()
        res = []
        while not dagItr.isDone():
            dagItr.getPath(dagPath)
            dagNode.setObject(dagPath)
            if dagNode.isInstanced():
                res.append( dagNode.fullPathName() )
            dagItr.next()
        if res == []:
            self.mayaPrint("No Instance Copy Object",printInWin)
        else:
            for obj in res:
                self.mayaWarning("Instance Copy Object <%s>"%(obj),printInWin,command="from maya import cmds\ncmds.select('%s')"%(obj) )
        
        return res
        
    #down form here is control method
    def qa_doClearWindow(self):
        "Delete all user open panel "
        panel = mc.getPanel(all=True)
        #panel = mc.getPanel(inv=True)
        for pan in panel:
            winName = pan + "Window"
            isScriptPan = re.search("^scriptEditorPanel",pan)
            if mc.window(winName, exists=True) and isScriptPan==None:
                mc.deleteUI(winName, window=True)
        return True
        
    def qa_subdMeshto1(self):
        allMesh = mc.ls(type="mesh")
        if allMesh!=[]:
            mc.displaySmoothness(allMesh,divisionsU=0,divisionsV=0,pointsWire=4,pointsShaded=1,polygonObject=1)
        return True
        
    def qa_setFourView(self):
        mel.eval( 'setNamedPanelLayout "Four View"' )
        return True
        
    def qa_wireframeDisplay(self):
        try:
            all = mc.getPanel(type="modelPanel")
            for p in all:
                mc.modelEditor(p,edit=True,displayAppearance="wireframe",displayLights="default") 
            return True
        except:
            return False
    def qa_wireframeOnShaded(self):
        try:
            all = mc.getPanel(type="modelPanel")
            for p in all:
                wos=mc.modelEditor(p,q=True,wos=True)
                if(wos):
                    mc.modelEditor(p,e=True,wos=0)
            return True
        except:
            return False
            
    def qa_fitAllView(self):
        all = mc.getPanel(type="modelPanel")
        for p in all:
            panelCam = mc.modelPanel(p,q=True,cam=1)
            mc.viewFit(panelCam ,all=True)
        return True
        
QualityAssuranceCls = QualityAssurance()